<template>
  <el-card shadow="never">
    <div slot="header">
      <span>{{pageTitle}}</span>
    </div>
    <el-divider content-position="left">核查计划信息</el-divider>
    <el-row>
      <el-form
        class="table_form_wrap"
        ref="planForm"
        :model="planForm"
        :rules="formValidate"
        label-width="100px"
      >
        <el-col :span="12">
          <el-form-item label="计划名称" prop="planName">
            <el-input
              v-model.trim="planForm.planName"
              placeholder="请输入计划名称"
              show-word-limit
              maxlength="50"
            />
          </el-form-item>
          <el-form-item label="核查时间" prop="planYear">
            <el-date-picker
              v-model="planForm.planYear"
              value-format="yyyy"
              type="year"
              placeholder="选择年"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划拟定人" prop="createUser">
            <el-input
              :value="USER_INFO.userName || ''"
            />
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <el-divider content-position="left">核查供应商明细</el-divider>
    <basic-table
      showTableIndex
      showActionCol
      :headerBeyondHide="false"
      :loading="tableInfo.loading"
      :columns="tableInfo.columns"
      :dataSource="tableInfo.list"
      :maxTableHeight="500"
      :actionColWidth="80"
      :actionRender="renderTableBtnAction"
    >
      <div slot="content_context">
        <el-button
          size="mini"
          type="primary"
          @click="handleAddSupplier"
          >添加供应商</el-button>
        <el-button
          size="mini"
          type="primary"
          :loading="exportLoading"
          @click="handleExportFile"
          >批量导出</el-button>
        <el-upload
          class="upload"
          action="/srm-export/import/supervision-supplier"
          accept=".xls, .xlsx"
          :on-success="uploadsuccess"
          :before-upload="beforeUpload"
          :on-error="uploadError"
          :show-file-list="false"
        >
          <el-button
            size="mini" type="primary"
            :loading="importLoading"
            >批量导入</el-button
          >
        </el-upload>
        <el-button
          size="mini"
          class="right-btn"
          @click="handleConfigTableColumns"
          >字段显示设置</el-button>
      </div>
    </basic-table>
    <el-divider />
    <el-row type="flex" justify="center" class="footer">
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">提交</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSave">暂存</el-button>
      <el-button @click="handleBack">返回</el-button>
    </el-row>
    <ConfigTableColumnsDialog
      :menuId="MENU_ID"
      v-if="fieldSettingVisible"
      :dialogVisible="fieldSettingVisible"
      @handleClose="handleConfigTableColumnsDialogClose"
      @handleSubmit="hanldSubmitTableColumnsConfig" />
    <SelectSupplier :supplierVisible.sync="supplierVisible" @getSupplierList="getSupplierList" />
    <HrUserDialog
      :isVisit="true"
      :hrUserVisible.sync="hrDialogVisible"
      :personList="selectRow.checkUserCode ? selectRow.checkUserCode.split(',').filter(item => item != '')  : []"
      @handle-select="handleGetUserList"
    />
  </el-card>
</template>
<script>
import { getTableAction } from '@/pages/supplier/utils/btnsUtils';
import { createExcelByExport, setAuthBtnId } from '@/utils/bizUtils';
import BasicTable from '@/components/skusTable';
import HrUserDialog from '@/pages/supplier/components/SelectHrUser'
import ConfigTableColumnsDialog from '@/pages/supplier/components/configTableColumnsDialog';
import SelectSupplier from './components/SelectQualifiedSupplier';
import { getListColumnSettings } from '@/api/supplier/components';
import {
  batchExportPlanService,
  stashCheckPlanService,
  submitCheckPlanService,
  queryCheckPlanListService,
  queryCheckSupplierDetailService
} from '@/api/supplier/supervision/checkPlan';
import {
  CHECK_TIME_TYPE_OPTIONS,
  MONTH_OPTIONS,
  QUARTER_OPTIONS,
  HALF_YEAR_OPTIONS,
  YEAR_OPTIONS,
  DEPARTMENT_OPTIONS,
  WHETHER_OPTIONS,
  CHECK_TYPE_OPTIONS,
  EXCEPTION_TYPE_OPTIONS
} from '../constants'
import { MENU_ID } from './constants'

const USER_INFO = localStorage.userInfo ? JSON.parse(localStorage.userInfo) : {};
export default {
  components: {
    BasicTable,
    ConfigTableColumnsDialog,
    SelectSupplier,
    HrUserDialog
  },
  data () {
    return {
      USER_INFO,
      timeObj: {
        1: MONTH_OPTIONS,
        2: QUARTER_OPTIONS,
        3: HALF_YEAR_OPTIONS,
        4: YEAR_OPTIONS,
      },
      MENU_ID,
      fieldSettingVisible: false,
      supplierVisible: false,
      hrDialogVisible: false,
      selectRow: {},
      planId: '',
      planForm: {
        planName: '',
        planYear: '',
        createUser: '',
        createTime: '',
      },
      formValidate: {
        planName: [
          { required: true, message: '计划名称不能为空', trigger: 'blur' }
        ],
        planYear: [
          { required: true, message: '核查时间不能为空', trigger: 'blur' }
        ],
      },
      tableInfo: {
        list: [],
        selection: [],
        columns: [],
        loading: false
      },
      submitLoading: false,
      exportLoading: false,
      importLoading: false,
      pickerOptions: {
        disabledDate (time) {
          const year = new Date().getFullYear()
          return (
            time.getFullYear() < year
          )
        }
      }
    }
  },
  computed: {
    pageTitle () {
      return this.planId ? '修改核查计划' : '新建核查计划';
    }
  },
  created () {
    this.getColSettings()
    const { id } = this.$route.query;
    if (id) {
      this.planId = id;
      // 获取核查计划信息
      this.getPlanInfoData()
      // 获取核查供应商明细
      this.getSupplierDetail()
    }
  },
  methods: {
    // 渲染操作列
    renderTableBtnAction (h, { row }) {
      const actionList = [
        { label: '删除', method: this.handleDelete, hasAuth: true }
      ];
      return getTableAction({ h, row, actionList, showBtn: this.showBtn });
    },
    // 获取核查计划信息
    async getPlanInfoData () {
      setAuthBtnId();
      const res = await queryCheckPlanListService(
        { id: this.planId },
        // state => { this.tableInfo.loading = state }
      );
      if (res?.result) {
        const {
          planName,
          planYear,
          createUser,
          createTime
        } = res.result.records[0];
        this.planForm = {
          planName,
          planYear: planYear ? planYear.toString() : '',
          createUser,
          createTime
        }
      }
    },
    // 获取核查供应商信息
    async getSupplierDetail () {
      const res = await queryCheckSupplierDetailService(
        { planId: this.planId },
        state => { this.tableInfo.loading = state }
      );
      if (res?.result) {
        this.tableInfo.list = res.result.records
      }
    },
    // 添加人员回调
    handleGetUserList (val) {
      // checkUser checkUserCode
      let checkUserCodeList = this.selectRow.checkUserCode ? this.selectRow.checkUserCode.split(',') : []
      let checkUserNameList = this.selectRow.checkUser ? this.selectRow.checkUser.split(',') : []
      const { row, type } = val
      if (type == 'select') {
        const { jobNumber, userName } = row;
        checkUserCodeList.push(jobNumber)
        checkUserNameList.push(userName)
      } else {
        checkUserNameList = checkUserNameList.filter(item => item !== row.jobNumber)
        checkUserCodeList = checkUserCodeList.filter(item => item !== row.userName)
      }
      this.$set(this.selectRow, 'checkUserCode', checkUserCodeList.join(','));
      this.$set(this.selectRow, 'checkUser', checkUserNameList.join(','));
    },
    // 展示人选选择框
    showHrDialog (row) {
      this.selectRow = row;
      this.hrDialogVisible = true
    },
    // 添加供应商回调
    getSupplierList (val) {
      const supplierCodeList = this.tableInfo.list.map(item => item.supplierCode)
      if (val?.length) {
        const newSupplirs = val.filter(item => !supplierCodeList.includes(item.supplierCode))
        this.tableInfo.list = newSupplirs.concat(this.tableInfo.list)
      }
    },
    // 获取列表配置
    async getColSettings () {
      const { status, result = [] } = await getListColumnSettings({ menuId: MENU_ID })
      if (status === '0') {
        this.setTableColumns(result)
      }
    },
    // 应用列表配置
    setTableColumns (data) {
      const columnList = data.filter(i => i.isShow).map(i => {
        return {
          title: i.label,
          key: i.prop,
          width: i.width,
          required: i.isRequired
        }
      })
      // 是否核查 isCheck 是否季节性商品 isSeasonalGoods 是否库存商品 isStockGoods
      const whetherFileList = ['isCheck', 'isSeasonalGoods', 'isStockGoods']
      const areaFileList = ['provinceName', 'cityName', 'areaName', 'noCheckReason']
      this.tableInfo.columns = columnList.map((i) => {
        // 异常类型
        if (i.key === 'exceptionType') {
          i.render = (h, { row }) => {
            return <el-select disabled size='mini' v-model={row.exceptionType}>
              { EXCEPTION_TYPE_OPTIONS.map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
            </el-select>
          }
        }
        // 核查部门
        if (i.key === 'deptId') {
          i.render = (h, { row }) => {
            return <el-select size='mini' v-model={row.deptId}>
              { DEPARTMENT_OPTIONS.map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
            </el-select>
          }
        }
        // 核查方式
        if (i.key === 'checkType') {
          i.render = (h, { row }) => {
            return <el-select size='mini' v-model={row.checkType}>
              { CHECK_TYPE_OPTIONS.map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
            </el-select>
          }
        }
        // 核查维度
        if (i.key === 'checkDimension') {
          i.render = (h, { row }) => {
            return <el-select size='mini' v-model={row.checkDimension}>
              { CHECK_TIME_TYPE_OPTIONS.map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
            </el-select>
          }
        }
        // 核查时间
        if (i.key === 'checkTimePeriod') {
          i.render = (h, { row }) => {
            return <el-select size='mini' v-model={row.checkTimePeriod}>
              { row.checkDimension && this.timeObj[row.checkDimension].map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
            </el-select>
          }
        }
        // 核查人id
        if (i.key === 'checkUserCode') {
          i.render = (h, { row }) => {
            return <el-input
              size='mini'
              v-model={row.checkUser}
              placeholder="请选择核查人"
              suffix-icon="el-icon-search"
              onFocus={() => { this.showHrDialog(row) }}
            />
          }
        }
        // 是否选项
        if (whetherFileList.includes(i.key)) {
          i.render = (h, { row }) => {
            return <el-select size='mini' v-model={row[i.key]}>
              { WHETHER_OPTIONS.map(item => <el-option key={item.value} value={item.value} label={item.label} />) }
            </el-select>
          }
        }
        // 省市区 不核查原因
        if (areaFileList.includes(i.key)) {
          i.render = (h, { row }) => {
            return <el-input size='mini' v-model={row[i.key]} />
          }
        }
        return i
      })
    },
    // 列表字段配置
    handleConfigTableColumns () {
      this.fieldSettingVisible = true;
    },
    // 字段显示设置弹窗关闭
    handleConfigTableColumnsDialogClose () {
      this.fieldSettingVisible = false;
    },
    // 提交字段显示设置
    hanldSubmitTableColumnsConfig (data) {
      this.setTableColumns(data)
      this.fieldSettingVisible = false;
    },
    // 批量导出
    async handleExportFile () {
      const res = await batchExportPlanService({}, state => { this.exportLoading = state })
      if (res) {
        createExcelByExport({ res, excelTitle: '供应商列表' })
      }
    },
    beforeUpload () {
      this.importLoading = true;
      this.tableInfo.loading = true;
    },
    uploadsuccess (res) {
      this.importLoading = false;
      this.tableInfo.loading = false;
      if (res && res.status == 0) {
        this.$message.success('导入成功')
        this.tableInfo.list = res.result;
      }
    },
    uploadError () {
      this.importLoading = false;
      this.tableInfo.loading = false;
      this.$message.error('导入异常')
    },
    // 添加供应商
    handleAddSupplier () {
      this.supplierVisible = true;
    },
    // 删除供应商
    handleDelete (row) {
      this.tableInfo.list = this.tableInfo.list.filter(item => item.supplierCode != row.supplierCode)
    },
    async handleSave () {
      const saveData = {
        detailList: this.tableInfo.list,
        planName: this.planForm.planName,
        planYear: this.planForm.planYear,
      }
      if (this.planId) {
        saveData.id = this.planId;
      }
      const res = await stashCheckPlanService(saveData, state => { this.submitLoading = state })
      if (res) {
        this.$message.success('暂存成功')
        this.handleBack()
      }
    },
    handleSubmit () {
      this.$refs.planForm.validate(valid => {
        if (valid) {
          if (this.tableInfo.list.length === 0) {
            return this.$message.warning('核查供应商明细不能为空')
          }
          const submitData = {
            detailList: this.tableInfo.list,
            planName: this.planForm.planName,
            planYear: this.planForm.planYear
          }
          if (this.planId) {
            submitData.id = this.planId;
          }
          this.submitAciton(submitData)
        }
      })
    },
    async submitAciton (data) {
      const res = await submitCheckPlanService(data, state => { this.submitLoading = state })
      if (res) {
        this.$message.success('提交成功')
        this.handleBack()
      }
    },
    handleBack () {
      this.$router.go(-1)
    }
  }
}
</script>
<style scoped>
.upload {
  display: inline;
  margin: 0 10px;
}
.right-btn {
  float: right;
}
</style>
